package org.ttitfly.workflow;

import java.util.Map;
import java.util.Stack;

import org.ttitfly.workflow.engine.ProcessFactory;
import org.ttitfly.workflow.engine.persistence.PersistenceService;
import org.ttitfly.workflow.exception.NoSessionConnectedException;


/**
 * 线程会话管理器
 * 
 * <pre>
 * 针对每个请求线程维持一个会话栈
 * </pre>
 * 
 * @author 潘海春
 * @version 2009-1-11
 * @see SessionEstablishment
 */
public class ThreadSessionEstablishment extends SessionHolder implements
		SessionEstablishment {

	/**
	 * 流程工厂
	 */
	private ProcessFactory processFactory;

	/**
	 * 持久化服务
	 */
	private PersistenceService persistenceService;

	/**
	 * 构造函数
	 * 
	 * @param processFactory
	 */
	public ThreadSessionEstablishment(ProcessFactory processFactory,
			PersistenceService persistenceService) {
		if (processFactory == null) {
			throw new IllegalArgumentException("参数[processFactory]不能为空！");
		}
		if (persistenceService == null) {
			throw new IllegalArgumentException("参数[persistenceService]不能为空！");
		}
		this.processFactory = processFactory;
		this.persistenceService = persistenceService;
	}

	@Override
	public Session connect(String principal, Map<String, Object> data) {
		Stack<Session> sessionStack = currentSessionStack();
		if (sessionStack == null) {
			// 当前第一次请求初始化会话栈
			sessionStack = new Stack<Session>();
			setCurrentSessionStack(sessionStack);
		}
		Session session = new ExecuteContext(principal, data, processFactory, persistenceService, this);
		sessionStack.push(session);
		return session;
	}

	@Override
	public void disconnect() throws NoSessionConnectedException {
		Stack<Session> sessionStack = currentSessionStack();
		if (sessionStack == null || sessionStack.isEmpty()) {
			throw new NoSessionConnectedException();
		}
		// 从栈里面弹出最近的会话
		sessionStack.pop();
	}

}
